package com.app.aipass.fragment.main;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.app.aipass.BR;
import com.app.aipass.R;
import com.app.aipass.app.AppApplication;
import com.app.aipass.app.AppViewModelFactory;
import com.app.aipass.databinding.FragmentTabMyBinding;
import com.app.aipass.entity.Message;
import com.app.aipass.entity.UserEntity;
import com.app.aipass.utils.GlideUtils;
import com.app.aipass.utils.SpUtils;
import com.app.aipass.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.RxSubscriptions;

/**
 * @author: woking
 * @date: 2021/6/7
 * @description：
 */
public class MyFragment extends BaseFragment<FragmentTabMyBinding, MyViewModel> {
    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_tab_my;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public MyViewModel initViewModel()
    {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用NetWorkViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(MyViewModel.class);
    }
    private Disposable mSubscription;
    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mSubscription != null)
        {
            RxSubscriptions.remove(mSubscription);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.e("TAG","=======MyFragment========onResume=====");
        if(!Utils.isLogin())
        {
            binding.loginTv.setText("授权登录");
            binding.userPhoneTv.setText("请授权登录");
        }
        else
        {
            binding.loginTv.setText("切换账号");
        }
    }

    @Override
    public void initData() {
        super.initData();
//        viewModel.requestNetWork();
        UserEntity userEntity = ((AppApplication)AppApplication.getInstance()).getUserEntity();
        if(userEntity != null)
        {
            binding.userPhoneTv.setText(userEntity.nickname);
        }
        if(!Utils.isLogin())
        {
            binding.loginTv.setText("授权登录");
        }
        else
        {
            binding.loginTv.setText("切换账号");
        }
        viewModel.baseUser();
        viewModel.mUserInfoEntity.observe(this, new Observer<UserEntity>() {
            @Override
            public void onChanged(UserEntity userInfoEntity) {
                binding.userPhoneTv.setText(userInfoEntity.show_name);
                SpUtils.put(getActivity(),"authentication",userInfoEntity.authentication);
//                if(TextUtil.isEmpty(userInfoEntity.nickname))
//                {
//                    binding.userPhoneTv.setText(userInfoEntity.realname);
//                }
//                String path = "https://cdn1.tuochennet.cn/9f4f38c785d86e207038906883fb3f2a.png";
                GlideUtils.getInstances().loadToCircle(getContext(),userInfoEntity.pic,R.mipmap.icon_mine_head).into(binding.headerImg);
//                GlideUtils.getInstances().loadRoundCornerImg(getContext(),binding.headerImg,90,userInfoEntity.pic,R.mipmap.icon_head);
                viewModel.getZTXShopToken();
            }
        });
        mSubscription = RxBus.getDefault().toObservable(Message.class)
                .observeOn(AndroidSchedulers.mainThread()) //回调到主线程更新UI
                .subscribe(new Consumer<Message>() {
                    @Override
                    public void accept(final Message message) throws Exception {
                        Log.e("TAG","===============message=============="+message.getName());
                        if(message.getName().equals("start_login"))
                        {
                            binding.loginTv.setText("切换账号");
                            viewModel.baseUser();
                        }
                        else if(message.getName().equals("MainActivity_index_3"))
                        {
                            if(viewModel.mUserInfoEntity.getValue() == null && Utils.isFastClick())
                            {
                                viewModel.baseUser();
                            }
                        }
                        else if(message.getName().equals("login_out"))
                        {
                            binding.loginTv.setText("授权登录");
                            binding.userPhoneTv.setText("请授权登录");
                        }
                    }
                });
        //将订阅者加入管理站
        RxSubscriptions.add(mSubscription);
        binding.loginTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Intent intent = new Intent();
//                //第一种方式
//                ComponentName cn = new ComponentName("com.zhilingshenghuo.app", "com.zhitianxia.app.activity.SplashActivity");
//                try {
//                    intent.setComponent(cn);
//                    //name===CSC code:6c0271860fad358708fb72f7f89e744e apptag:  com.cscex.app
//                    intent.putExtra("name", "CSC");
//                    intent.putExtra("type", "NEW_CSC");
//                    intent.putExtra("code", "6c0271860fad358708fb72f7f89e744e");
//                    intent.putExtra("apptag", "com.example.csc");//com.example.csc   com.cscex.app
//                    startActivityForResult(intent, 100);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }

                try {
//                    if(!isAvilible(getContext(), "com.zhilingshenghuo.app"))
//                    {
//                        ToastUtil.showToast("请安装智领生活APP！");
//                        return;
//                    }
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_MAIN);
                    intent.addCategory(Intent.CATEGORY_LAUNCHER);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                            | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
//                    intent.setComponent(new ComponentName("com.app.csc", "com.app.csc.activity.SplashActivity"));
                    intent.setComponent(new ComponentName("com.app.newcsc", "com.app.newcsc.activity.SplashActivity"));

                    intent.putExtra("name", "aiPass");
                    intent.putExtra("type", "NEW_AI");
                    intent.putExtra("code", "6c0271860fad358708fb72f7f89e744e");
                    intent.putExtra("apptag", "com.app.aipass");//com.example.csc   com.cscex.app

                    startActivityForResult(intent, 100);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private boolean isAvilible(Context context, String packageName){
        final PackageManager packageManager = context.getPackageManager();//获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);//获取所有已安装程序的包信息
        List<String> pName = new ArrayList<String>();//用于存储所有已安装程序的包名
        //从pinfo中将包名字逐一取出，压入pName list中
        if(pinfo != null)
        {
            for(int i = 0; i < pinfo.size(); i++)
            {
                String pn = pinfo.get(i).packageName;
                pName.add(pn);
            }
        }
        return pName.contains(packageName);//判断pName中是否有目标程序的包名，有TRUE，没有FALSE
    }
}